//
//  ClubHomeNewRecommendViewController.swift
//  ClubanGame
//
//  Created by Apple on 2024/8/7.
//  Copyright © 2024 94Wan. All rights reserved.
//

import UIKit
import JXSegmentedView

private let headerID    = "ClubNewRecommendTopView"

class ClubHomeRecommendViewController: ClubBaseViewController {

    private lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .grouped)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = .clear
        tableView.showsVerticalScrollIndicator = false
        tableView.register(ClubNewGongNengView.self, ClubNewRecommendGameView.self, ClubNewHotGameView.self,ClubNewDiscoverMoreView.self)
        tableView.register(ClubHomeTitleHeaderView.self, forHeaderFooterViewReuseIdentifier: headerID)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.separatorStyle = .none
        return tableView
    }()
    private var pageIndex = 1
    private var topView = ClubHomeInfoTopView()
    private var dataModel: ClubNewHomeModel?
    private var discoverModels = [ClubNewHomeGameModel]()
    private var gongNengModels: [ClubHomeGongNengModel] = [
        ClubHomeGongNengModel(id: 100, name: "游戏工具", image: "GongNeng_games"),
        ClubHomeGongNengModel(id: 101, name: "游戏论坛", image: "GongNeng_community"),
        ClubHomeGongNengModel(id: 102, name: "每日签到", image: "GongNeng_dailySign"),
        ClubHomeGongNengModel(id: 103, name: "积分商城", image: "GongNeng_store")
    ]
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
        
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = "#F7F8FA".toColor
        view.subviews{
            tableView
        }
        
        loadData()
        
        if #available(iOS 15.0, *) {
            self.tableView.sectionHeaderTopPadding = 0
        } else {
            // Fallback on earlier versions
        }

        tableView.fillContainer()
        
        topView.frame = CGRect(x: 0, y: 0, width: .screenWidth, height: 170.0.Scale)
        tableView.tableHeaderView = topView
        
        tableView.refresh_loadMore {
            self.loadMoreData()
        }.refresh_pull {
            self.loadNewData()
        }
        
        //========noti==========
        NotificationCenter.default.addObserver(self, selector: #selector(toDetailVc), name: .toGameDetailVC, object: nil)
    }
    
    @objc private func toDetailVc(noti: Notification) {
        
        if let infoId = noti.userInfo?["infoID"] as? Int {
            pushToDetailVC(infoId: infoId)
        }
    }

    private func pushToDetailVC(infoId: Int){
        
        let detailVC = ClubGameDetailViewController()
        detailVC.gameId = String(infoId)
        self.navigationController?.pushViewController(detailVC, animated: true)
    }
}

//MARK: - loadData
extension ClubHomeRecommendViewController {

    private func loadData(){

        Task {
            let models = await network.requestMoreData(.homeRecommend(page: pageIndex),type: ClubNewHomeModel.self,isShowError: false)
            tableView.refresh_end()
            if models.isSuccess, let model = models.model {
                self.dataModel = model
                
                if let dataArr = model.data, dataArr.count > 0 {
                    for md in dataArr {
                        var mod = md
                        mod.randomInt = Int.random(in: 0...2)
                        mod.borderRandomInt = Int.random(in: 0...9)
                        self.discoverModels.append(mod)
                        
                    }
                }
                self.topView.bannarModel = model.slide
                self.tableView.reloadData()
            }
        }

    }
    
    
    @objc private func loadNewData() -> () {
        pageIndex = 1
        self.discoverModels.removeAll()
        loadData()
    }
    
    @objc private func loadMoreData() -> () {
        pageIndex += 1
       
        Task {
            let models = await network.requestMoreData(.homeRecommend(page: pageIndex),type: ClubNewHomeModel.self,isShowError: false)
            tableView.refresh_end()
            if models.isSuccess, let model = models.model {
                if let dataArr = model.data, dataArr.count > 0 {
                    for md in dataArr {
                        var mod = md
                        mod.randomInt = Int.random(in: 0...2)
                        mod.borderRandomInt = Int.random(in: 0...9)
                        self.discoverModels.append(mod)
                    }
                }else {
                    self.tableView.refresh_end(true)
                }
                self.tableView.reloadData()
            }
        }
        
    }
}


//MARK: - UITableViewDelegate, UITableViewDataSource
extension ClubHomeRecommendViewController: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 5
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        if section == 4 {
            return discoverModels.count
        }
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "ClubNewGongNengView", for: indexPath) as! ClubNewGongNengView
            cell.sourceData = self.gongNengModels
            cell.rankArray = dataModel?.newgame_top
            cell.clickCateBlock = { type in
                if type == 100 {
                    //游戏工具
                    self.navigationController?.pushViewController(ClubGameToolsViewController(), animated: true)
                }else if type == 101 {
                    //游戏论坛
                    if let tabBarController = self.tabBarController as? ClubTabBarViewController {
                        tabBarController.selectedTabController(index: 2)
                        DispatchQueue.main.asyncAfter(deadline: .now()+0.5) {
                            NotificationCenter.default.post(name: .toLuntanListVC, object: nil)
                        }
                    }
                }else if type == 102 {
                    //每日签到
                    guard let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 else {
                        self.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
                        return
                    }
                    self.navigationController?.pushViewController(ClubSigninViewController(), animated: true)
                }else if type == 103 {
                    //积分商城
                    guard let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 else {
                        self.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
                        return
                    }
                    self.navigationController?.pushViewController(ClubIntegralStoreViewController(), animated: true)
                }
            }
            return cell
        } else if indexPath.section == 1{
            let cell = tableView.dequeueReusableCell(withIdentifier: "ClubNewRecommendGameView", for: indexPath) as! ClubNewRecommendGameView
            cell.dataSource = dataModel?.tuijian
            return cell
        } else if indexPath.section == 2{
            let cell = tableView.dequeueReusableCell(withIdentifier: "ClubNewHotGameView", for: indexPath) as! ClubNewHotGameView
            cell.dataSource = dataModel?.remen
            return cell
        } else if indexPath.section == 3{
            let cell = tableView.dequeueReusableCell(withIdentifier: "ClubNewRecommendGameView", for: indexPath) as! ClubNewRecommendGameView
            cell.dataSource = dataModel?.newgame_later
            return cell
        } else{
            let cell = tableView.dequeueReusableCell(withIdentifier: "ClubNewDiscoverMoreView", for: indexPath) as! ClubNewDiscoverMoreView
            cell.model = discoverModels[indexPath.row]
            return cell
        }
        
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if indexPath.section == 4 {
            let infoId = discoverModels[indexPath.row].id
            pushToDetailVC(infoId: infoId)
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 {
            return 410.0.Scale
        }else if indexPath.section == 1 {
            return 255.0.Scale
        }else if indexPath.section == 2 {
            return 180.0.Scale
        }else if indexPath.section == 3 {
            return 255.0.Scale
        }else{
            return 230.0.Scale
        }
        
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: headerID) as! ClubHomeTitleHeaderView
        if section == 1 {
            header.titleString = "小编推荐"
        }else if section == 2 {
            header.titleString = "热门游戏"
        }else if section == 3 {
            header.titleString = "近期新游"
        }else if section == 4 {
            header.titleString = "探索更多"
        }
        return header
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        if section == 0 {
            return 0
        }        
        return 46.0.Scale
    }
}

extension ClubHomeRecommendViewController:JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return view
    }
}
